import type { Context } from 'koa'

import { Post } from '../../router'

import { database } from '../../database'

// import Login from '../db/Login'
// import User from '../db/User'

import { Login, User } from '../db'

import { result } from '../index'

import { genSign, uuid } from '../../util'

export default class LoginInfo {
  @Post('/login')
  static async login(ctx: Context) {
    try {
      const { username, password } = ctx.request.body as { [k: string]: string }
      if (!username || !password) {
        return ctx.throw(400, '用户名或者密码不能为空')
      }
      const db = database.getRepository(Login)
      if (!db) {
        return ctx.throw(500, '网络链接错误,-101')
      }
      const user =
        (await db.findOneBy({
          username
        })) || null
      if (user && user.password === password) {
        const time = Date.now() + 24 * 60 * 60 * 1000
        const token = 'Bearer ' + genSign({ id: user.id, time })
        const data = {
          id: user.id,
          token
        }
        ctx.body = result({ data })
        return
      }
    } catch (error) {
      return ctx.throw(500, error)
    }
    return ctx.throw(400, '用户名或者密码错误')
  }

  @Post('/register')
  static async register(ctx: Context) {
    try {
      const { username, password } = ctx.request.body
      if (!username || !password) {
        return ctx.throw(400, '用户名或者密码不能为空')
      }
      const db = database.getRepository(Login)
      if (!db) {
        return ctx.throw(500, '网络链接错误-101')
      }
      const isUser = await db.findOneBy({
        username
      })
      if (isUser) return ctx.throw(400, '注册失败, 用户已存在')
      const login = new Login()
      login.id = uuid()
      login.username = username
      login.password = password
      const res = await db.save(login)
      const newUser = new User()
      newUser.id = res.id
      newUser.login = res
      const dbUser = database.getRepository(User)
      const user = await dbUser.save(Object.assign(newUser, updataUser()))
      if (!user || !res) return ctx.throw(500, '注册失败')
      const time = Date.now() + 2 * 60 * 60 * 1000
      const token = 'Bearer ' + genSign({ id: user.id, time })
      ctx.body = result({
        data: { token, id: user.id }
      })
    } catch (error) {
      return ctx.throw(500, error)
    }
  }
}

const arr = [
  '胡迪',
  '提莫',
  '安迪',
  '牧羊',
  '巴斯',
  '安妮',
  '蜜桃',
  '凤梨',
  '雪糕',
  '柯南',
  '灰原',
  '步美',
  '元太',
  '光彦',
  '园子',
  '京极',
  '安室',
  '朱迪',
  '琴酒',
  '伏特加',
  '苦艾酒',
  '毛利兰',
  '上尉',
  '秋田',
  '逍遥'
]

function updataUser() {
  const i = Math.floor(Math.random() * arr.length)
  const num = Math.floor(Math.random() * 35)
  return {
    nickname: arr[i],
    age: num < 16 ? 16 : num,
    sex: Math.round(Math.random()),
    url: 'https://img.yzcdn.cn/vant/cat.jpeg'
  }
}
